package com.tianyu.service.mqtt.handler.inbound.next;

import com.alibaba.fastjson2.JSONObject;
import com.tianyu.common.AppConstants;
import com.tianyu.model.dto.UavRealtimeInfoDTO;
import com.tianyu.service.cache.DataCacheService;
import com.tianyu.service.mqtt.common.MqttMessageChannel;
import com.tianyu.service.mqtt.handler.outbound.IMqttOutboundThird01Gateway;
import com.tianyu.service.mqtt.model.def.TianyuPB;
import com.tianyu.service.mqtt.model.dto.StateResponse;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;


/**
 * @author swyan
 */
@Component
@Slf4j
public class BoxStateHandler {

    @Resource
    private IMqttOutboundThird01Gateway mqttOutboundThird01Gateway;

    @SneakyThrows
    @ServiceActivator(inputChannel = MqttMessageChannel.ChannelName.INBOUND_UAV_STATE)
    protected void messageReceived(Message<byte[]> message) {
        MessageHeaders headers = message.getHeaders();
        String topic = Objects.requireNonNull(headers.get(MqttHeaders.RECEIVED_TOPIC)).toString();
        final Integer companyId = Integer.parseInt(topic.split("/")[3]);
        final String deviceSn = topic.split("/")[4];
        byte[] content = message.getPayload();
        final TianyuPB.TelemetryData telemetryData = TianyuPB.TelemetryData.parseFrom(content);
        DataCacheService.boxOsdMap.put(deviceSn,telemetryData);
        // log.info(telemetryData.toString());
        final JSONObject tianyuThirdAccessChannel = DataCacheService.tianyuThirdAccessChannelMap.get(companyId);
        if (tianyuThirdAccessChannel == null){
            return;
        }
        final String thirdAccessKey = tianyuThirdAccessChannel.getString("thirdAccessKey");
        String appKey = "c3pfZGFwZW5nQEA6MjAyNDA3MTE";

        final String batteryPower = telemetryData.getBatteryPower();
        final String[] batteryPowerSplit = batteryPower.split("_");
        final StateResponse stateResponse = StateResponse.newUavState(UavRealtimeInfoDTO.builder()
                .sn(telemetryData.getBoxSn())
                .executionsId(String.valueOf(telemetryData.getTaskId()))
                .longitude(telemetryData.getLng())
                .latitude(telemetryData.getLat())
                .altitude((double) telemetryData.getAltitude())
                .height((double) telemetryData.getUltrasonic())
                .batteryLife(!"".equals(batteryPower) ? (double) ((Integer.parseInt(batteryPowerSplit[0]) + Integer.parseInt(batteryPowerSplit[1])) / 2) : null)
                .distance((double) telemetryData.getAirFlyDistance())
                .duration((double) telemetryData.getAirFlyTimes())
                .attitudePitch((double) telemetryData.getPitch())
                .attitudeRoll((double) telemetryData.getRoll())
                .attitudeYaw((double) telemetryData.getYaw())
                .horizontalSpeed((double) telemetryData.getVelocity())
                .verticalSpeed((double) telemetryData.getAirspeed())
                .mode(telemetryData.getFlightMode())
                .dataTime(AppConstants.DATE_FORMAT.format(new Date(telemetryData.getTimestamp())))
                .build());
        mqttOutboundThird01Gateway.publish("sz/" + thirdAccessKey + "/uav", JSONObject.from(stateResponse).toJSONString().getBytes());
    }
}
